package dao.file;

import common.JdbcUtils;
import org.apache.commons.io.IOUtils;

import javax.sql.rowset.serial.SerialBlob;
import java.io.*;
import java.sql.*;

/**
 * 文件描述
 *
 * @Author 冯根源
 * @create 2020/4/2 14:57
 */
public class FileDao {
    public static void addFile() {
        Connection conn = null;
        PreparedStatement stm = null;
        try {
            conn = JdbcUtils.getConnection();
            String sql = "INSERT INTO t_file VALUES(?,?,?)";
            stm = conn.prepareStatement(sql);

            stm.setInt(1,1);

            stm.setString(2,"map.exe");

            // 把文件转化成byte[]
            byte[] bytes  = IOUtils.toByteArray(new FileInputStream("D:\\map.exe"));
            //使用byte创建blob
            Blob blob = new SerialBlob(bytes);
            stm.setBlob(3,
                    blob );
            stm.executeUpdate();
        } catch (SQLException | FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //从数据库读取文件
    public static void getFile() {
        Connection conn = null;
        PreparedStatement stm = null;
        ResultSet resultSet = null;
        try {
            String sql = "SELECT * FROM t_file ";
            conn = JdbcUtils.getConnection();
            stm = conn.prepareStatement(sql);
            //执行stm查询，得到ResultSet
            resultSet =stm.executeQuery();
            //获取resultSet中名为data的列数据
            if(resultSet.next()){
              Blob blob=  resultSet.getBlob("file");
              //把Blob变成硬盘上的文件
                InputStream blobInput = blob.getBinaryStream();
                OutputStream out = new FileOutputStream("c:/map.exe");
                IOUtils.copy(blobInput,out);

            }
        } catch (SQLException | FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(conn,stm,resultSet);
        }

    }

    public static void main(String[] args) {
        getFile();
    }
}
